package com.gohi.main.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class BdMapUtils {

	public static void main(String[] args) throws Exception {
		System.err.println(getpoint("上海"));
		//31.339919800888,121.49208325378   31.339444764386,121.49281587325
		
		//System.err.println(getmsg("31.339919800888,121.49208325378","31.339444764386,121.49281587325"));
	}

	public static String getmsg(String add1, String add2) throws Exception {
		String str = null;
		// 34.656800787697,119.26057354252&destinations=34.587062097341,119.17406939548
		String result = get("http://api.map.baidu.com/direction/v1/routematrix?origins="
				+ add1
				+ "&destinations="
				+ add2
				+ "&mode=walking&output=xml&ak=YyFOpb9jOrq5eEm3nT2A1YKH");
		Document doc = null;
		String lat = "", lng = "", t = "";
		System.err.println(result);
		doc = DocumentHelper.parseText(result); // 将字符串转为XML
		Element e = doc.getRootElement();
		int ct = 0;
		Iterator iters = e.elementIterator();
		while (iters.hasNext()) {
			Element itemEle = (Element) iters.next();
			Iterator iters1 = itemEle.elementIterator();

			while (iters1.hasNext()) {

				Element itemEle1 = (Element) iters1.next();

				Iterator iters2 = itemEle1.elementIterator();
				while (iters2.hasNext()) {
					Element itemEle2 = (Element) iters2.next();
					t = itemEle2.elementTextTrim("text");
					if (t != null) {
						if (ct == 0) {
							lat = "距离" + t;
							ct = ct + 1;
						} else if (ct == 1) {
							lat = lat + "步行需要" + t;
						}

					}

				}
			}
		}

		return lat;
	}

	/**
	 * 根据位置返回坐标
	 * 
	 * @param address
	 * @return
	 * @throws Exception
	 */
	public static String getpoint(String address) throws Exception {
		String str = null;
		URL url = new URL(
				"http://api.map.baidu.com/geocoder/v2/?address="
						+ address
						+ "&output=xml&ak=YyFOpb9jOrq5eEm3nT2A1YKH&callback=showLocation");
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setReadTimeout(5000);// 将读超时设置为指定的超时，以毫秒为单位。用一个非零值指定在建立到资源的连接后从
									// Input 流读入时的超时时间。如果在数据可读取之前超时期满，则会引发一个
									// java.net.SocketTimeoutException。
		con.setDoInput(true);// 指示应用程序要从 URL 连接读取数据。
		con.setRequestMethod("GET");// 设置请求方式
		if (con.getResponseCode() == 200) {// 当请求成功时，接收数据（状态码“200”为成功连接的意思“ok”）
			InputStream is = con.getInputStream();
			str = formatIsToString(is);
		}

		Document doc = null;
		String lat = "", lng = "";
		doc = DocumentHelper.parseText(str); // 将字符串转为XML
		Element e = doc.getRootElement();
		Iterator iters = e.elementIterator();
		while (iters.hasNext()) {
			Element itemEle = (Element) iters.next();
			Iterator iters1 = itemEle.elementIterator();

			while (iters1.hasNext()) {
				Element itemEle1 = (Element) iters1.next();
				if (lat == "") {
					lat = itemEle1.elementTextTrim("lat");
				}
				if (lng == "") {
					lng = itemEle1.elementTextTrim("lng");
				}

			}
		}
		str =  lng+ "," + lat;
		return str;
	}

	public static String formatIsToString(InputStream is) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int len = -1;
		try {
			while ((len = is.read(buf)) != -1) {
				baos.write(buf, 0, len);
			}
			baos.flush();
			baos.close();
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new String(baos.toByteArray(), "utf-8");
	}

	public static String get(String apiUrl) throws Exception {
		String str = null;
		URL url = new URL(apiUrl);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setReadTimeout(5000);// 将读超时设置为指定的超时，以毫秒为单位。用一个非零值指定在建立到资源的连接后从
									// Input 流读入时的超时时间。如果在数据可读取之前超时期满，则会引发一个
									// java.net.SocketTimeoutException。
		con.setDoInput(true);// 指示应用程序要从 URL 连接读取数据。
		con.setRequestMethod("GET");// 设置请求方式
		if (con.getResponseCode() == 200) {// 当请求成功时，接收数据（状态码“200”为成功连接的意思“ok”）
			InputStream is = con.getInputStream();
			str = formatIsToString(is);
		}
		return str;
	}
}
